import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../routes.dart';

class BuilderTool {
  static AsyncWidgetBuilder<T> futureBuild<T>(Function(T data) widgetBuilder,
      [Widget? emptyWidget]) {
    return (BuildContext context, AsyncSnapshot<T> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Container(
            width: 50,
            height: 50,
            child: Center(child: CircularProgressIndicator()));
      } else if (snapshot.connectionState != ConnectionState.done) {
        return Text('State: ${snapshot.connectionState}');
      } else if (snapshot.hasError) {
        return const Text('Error');
      } else if (!snapshot.hasData) {
        if (emptyWidget == null) {
          Get.toNamed(Routes.notFound);
        } else {
          return emptyWidget;
        }
      }
      return widgetBuilder(snapshot.data as T);
    };
  }

  static Image defImg() {
    return Image.asset("assets/images/logo.png");
  }

  static Widget markdownImageBuilder(Uri uri, String? title, String? alt) {
    return uri.toString().isEmpty
        ? defImg()
        : Image.network(uri.toString(),
            errorBuilder: (ctx, obj, stack) => defImg());
  }

  static Image networkImage(String url) {
    return Image.network(url, errorBuilder: (ctx, obj, trace) => defImg());
  }
}
